<!-- 上单表 -->
<template>
    <div class="purchase">
        <a-page-header
            style="border: 1px solid rgb(235, 237, 240);background:#fff"
            :title="`${storehouse}-下单表`"
            @back="() => $router.go(-1)"
        >
            <div class='table-page-search-wrapper'>
                <a-form layout='inline'>
                    <a-row :gutter='48'>
                        <a-col :md="8" :sm="24">
                            <a-form-item label="商品信息">
                                <a-select v-model="goodsCateId" placeholder="请选择" allowClear @change="selGoods">
                                    <a-select-option v-for="(item,i) in goodsList" :key="i" :value="item.id+','+item.cateId">{{item.name}}-{{item.cateName}}</a-select-option>
                                </a-select>
                            </a-form-item>
                        </a-col>
                        <a-col :md="8" :sm="24">
                            <a-form-item label="颜色">
                                <a-select v-model="colorId" placeholder="请选择" allowClear @change="getData">
                                    <a-select-option v-for="(item,i) in colorsList" :key="i" :value="item.id">{{item.name}}</a-select-option>
                                </a-select>
                            </a-form-item>
                        </a-col>
                        <a-col :md="8" :sm="24">
                            <a-form-item label="等级">
                                <a-select v-model="grade" placeholder="请选择" allowClear @change="getData">
                                    <a-select-option v-for="(item,i) in gradeList" :key="i" :value="item.id">{{item.name}}</a-select-option>
                                </a-select>
                            </a-form-item>
                        </a-col>
                        <a-col :md="8" :sm="24">
                            <a-form-item label="规格">
                                <a-select v-model="specId" placeholder="请选择" allowClear @change="getData">
                                    <a-select-option v-for="(item,i) in specList" :key="i" :value="item.id">{{item.name}}</a-select-option>
                                </a-select>
                            </a-form-item>
                        </a-col>
                        <a-col :md="8" :sm="24">
                            <a-form-item label="状态">
                                <a-select v-model="status" placeholder="请选择" allowClear @change="getData">
                                    <a-select-option v-for="(item,i) in statusList" :key="i" :value="item.id">{{item.name}}</a-select-option>
                                </a-select>
                            </a-form-item>
                        </a-col>
                        <!-- <a-col :md='16' :sm='24'>
                            <a-range-picker @change="onChange" :show-time="{ format: 'HH:mm:ss' }" />
                        </a-col> -->
                        <a-col :md='8' :sm='24'>
                            <a-form-item >
                            <a-button style="margin-right: 20px" type="primary" @click="getData()">查询</a-button>
                            <a-button icon="plus" @click="add()" >下单新增</a-button>
                            </a-form-item>
                        </a-col>
                    </a-row>
                </a-form>
            </div>  

            <a-table size="small" :columns="columns" :data-source="dataList" :loading="isload" @change="handleTableChange" :pagination="{ pageSize: 10, total: total ,showSizeChanger: true,pageSize: size}" border>
                <div slot="grade" slot-scope="grade" > 
                    <div v-for="(item,i) in gradeList" :key="i">
                        <a-tag v-if="item.name == grade" :color="colors[i%13]">{{item.name}} </a-tag>
                    </div>
                </div>
                <div slot="specId" slot-scope="specId">
                    <div v-for="(item,i) in specList" :key="i">
                        <a-tag v-if="item.id == specId" :color="colors[i%13]">{{item.name}} </a-tag>
                    </div>
                </div>
                <div slot="colorId" slot-scope="colorId">
                    <div v-for="(item,i) in colorsList" :key="i">
                        <a-tag v-if="item.id == colorId" :color="colors[i%13]">{{item.name}} </a-tag>
                    </div>
                </div>
                <div slot="lastTime" slot-scope="lastTime">   
                    <div>{{lastTime ? lastTime : '-'}}</div>
                </div>
                <div slot="latestTime" slot-scope="latestTime">   
                    <div>{{latestTime ? latestTime : '-'}}</div>
                </div>
                <div slot="status" slot-scope="status">
                    <div v-for="(item,i) in statusList" :key="i">
                        <a-tag v-if="item.id == status" :color="colors[i%13]">{{item.name}} </a-tag>
                    </div>
                </div>
                <template slot="operation" slot-scope="text, record">
                    <div class="editable-row-operations" v-if="services == '1'">
                        <a-button type="link" v-if="record.status == '2'" @click="serviceUpdate(record)">确认上单</a-button>
                        <a-popconfirm
                            title="是否确认删除当前数据?"
                            ok-text="Yes"
                            cancel-text="No"
                            @confirm="del(record)"
                            v-if="record.status == '0'"
                        >
                            <a-button class="errorColor" type="link">删除</a-button>
                        </a-popconfirm>
                    </div>
                    <div class="editable-row-operations" v-else>
                        <a-button type="link" v-if="record.status == '0'" @click="update(record,'1')">确认下单</a-button>
                        <a-button type="link" v-if="record.status == '1'" @click="update(record,'2')">确认发货</a-button>
                        <a-button type="link" v-if="record.status == '1'" @click="update(record)">编辑</a-button>
                    </div>
                </template>
                <template slot="footer" slot-scope="currentPageData">
                    累计下单金额：{{totalAmount}}
                </template>
            </a-table>
        </a-page-header>

        <!-- 下单新增 -->
        <a-modal
            title="下单新增"
            :visible="visible"
            :confirm-loading="confirmLoading"
            @ok="handleOk"
            @cancel="visible = false"
            >
            <div>
                <a-form :label-col="{ span: 6 }" :wrapper-col="{ span: 17 }">
                    <a-form-item label="商品信息" >
                        <a-select show-search  v-model="item.goodsId" @search="handleSearch" placeholder="请选择">
                            <a-select-option v-for="(itm) in goodDetailList" :value="itm.goodsId+','+itm.id+','+itm.goodsName+','+itm.cateName+','+itm.colorName+','+itm.grade+','+itm.specName+','+itm.remarks" :key="itm.id">{{itm.goodsName}}-{{itm.cateName}}-{{itm.colorName}}-{{itm.grade}}-{{itm.specName}}-{{itm.remarks}}</a-select-option>
                        </a-select>   
                    </a-form-item>
                    <a-form-item label="下单数量" >
                        <a-input v-model="item.purchaseQuantity" :placeholder="`请输入下单数量`" allow-clear ></a-input>
                    </a-form-item>
                </a-form>
            </div>
        </a-modal>

        <!-- 收货人员操作下单表 -->
        <a-modal
            :title="`${receiverStatus == '1' ? '确认下单' : receiverStatus == '2' ? '确认发货' : '编辑'}`"
            :visible="receiverVisible"
            :confirm-loading="receiverConfirmLoading"
            @ok="receiverHandleOk"
            @cancel="receiverVisible = false"
            >
            <div>
                <a-form :label-col="{ span: 6 }" :wrapper-col="{ span: 17 }">
                    <a-form-item label="最新底价" >
                        <a-input v-model="latestReservePrice" :placeholder="`请输入最新底价`" allow-clear ></a-input>
                    </a-form-item>
                    <a-form-item label="实际收货数量" v-if="receiverStatus == '2'">
                        <a-input v-model="receiveQuantity" :placeholder="`请输入实际收货数量`" allow-clear ></a-input>
                    </a-form-item>
                    <a-form-item label="备注" >
                        <a-input v-model="remarks" :placeholder="`请输入备注`" allow-clear ></a-input>
                    </a-form-item>
                </a-form>
            </div>
        </a-modal>

        <!-- 客服确认上单 -->
        <a-modal
            :title="`确认上单`"
            :visible="serviceVisible"
            :confirm-loading="serviceConfirmLoading"
            @ok="serviceHandleOk"
            @cancel="serviceVisible = false"
            >
            <div>
                <a-form :label-col="{ span: 6 }" :wrapper-col="{ span: 17 }">
                    <!-- <a-form-item label="实际上单数量" >
                        <a-input v-model="addStockQuantity" :placeholder="`请输入实际上单数量`" allow-clear ></a-input>
                    </a-form-item> -->
                </a-form>
            </div>
        </a-modal>
    </div>
</template>

<script>
import { columns } from './table';
import { columns1 } from './table1';
import { queryGoodsPurchaseForm , queryGoodsGeneral , queryGoodsCommonConfig , queryGoodsDetail , createGoodsPurchaseForm , updateGoodsPurchaseFormByReceiver , updateGoodsPurchaseFormByCustomer } from '@/api/newMall';
export default {
    data () {
        return {
            brandId: this.global.brandId,
            storehouse: JSON.parse(localStorage.getItem('storehouseName')),
            storehouseId: JSON.parse(localStorage.getItem('storehouseId')),
            areaId: '0', // 固定商品区
            colorId: undefined,
            colorsList: [],
            grade: undefined,
            gradeList: [],
            services: this.$store.getters.roles.indexOf('updateGoodsPurchaseFormByCustomer') != -1 ? '1' : '0',
            goodsCateId: undefined,
            goodsList: [],
            goodsId: undefined,
            cateId: undefined,
            specId: undefined,
            specList: [],
            status: undefined,
            statusList: this.$store.getters.roles.indexOf('updateGoodsPurchaseFormByCustomer') != -1 ? [
                { id: '0', name: '待下单'},
                { id: '1', name: '待发货'},
                { id: '2', name: '已发货'},
            ] : [
                { id: '0', name: '待处理'},
                { id: '1', name: '已下单'},
                { id: '2', name: '待收货'},
            ],
            startTime: '', // 开始时间
            endTime: '', // 结束时间
            page: 1,
            size: 10,
            total: 0,
            dataList: [],
            isload: false,
            columns: this.$store.getters.roles.indexOf('updateGoodsPurchaseFormByCustomer') != -1 ? columns : columns1,
            colors: ['blue','purple','cyan','green','orange','red','pink','brown','indigo','lime','purple','teal','yellow','amber'],
            totalAmount: 0, // 累计下单金额
            visible: false,
            confirmLoading: false,
            item: {
                purchaseQuantity: '',
                goodsId: '',
            },
            goodDetailList: [],
            receiverItem: {},
            receiverStatus: undefined,
            receiverVisible: false,
            receiverConfirmLoading: false,
            receiveQuantity: '', // 实际收货数量
            latestReservePrice: '', // 最新底价
            remarks: '', // 备注
            serviceVisible: false,
            serviceConfirmLoading: false,
            addStockQuantity: '',
            serviceItem: {},
            roleLength: this.$store.getters.roles.length,
            statisticalDate: this.$route.query.statisticalDate,
            // roles: this.$store.getters.roles
        };
    },
    async created(){
        try {
            await this.getGoods();
            await this.getDescription('3');
            await this.getDescription('4');
            await this.getDescription('2');
            this.getGoodDetails();
            this.getData();
        } catch (error) {
            this.$notification['error']({
                message: '提示',
                description: error,
                duration: 8,
            })
        }
    },
    methods: {
        // 获取商品选择列表
        getGoods(){
            let _this = this;
            return new Promise((resolve,reject) => {
                const params = {
                    'brandId': _this.brandId,
                    'status': '1',
                    'page': 0,
                    'size': 99,
                }
                queryGoodsGeneral(params)
                .then(res => {
                    if(res.success){
                        _this.goodsList = res.data.content;
                        resolve();
                    }else{
                        reject(res.errMessage)
                    }
                })
            })
        },
        // 选择商品
        selGoods(item){
            console.log(item,'item')
            if(item){
                this.goodsId = item.split(',')[0];
                this.cateId = item.split(',')[1];
            }else{
                this.goodsId = undefined;
                this.cateId = undefined;
            }
            this.getData();
        },
        async handleSearch(goodsName){
            console.log(goodsName,'name')
            await this.getGoodDetails(goodsName);
        },
        // 获取商品详情列表
        getGoodDetails(goodsName){
            let _this = this;
            return new Promise((resolve,reject) => {
                const params = {
                    'brandId': _this.brandId,
                    'goodsName': goodsName,
                    'status': '1',
                    'page': 0,
                    'size': 99,
                }
                queryGoodsDetail(params)
                .then(res => {
                    if(res.success){
                        _this.goodDetailList = res.data.content;
                        resolve();
                    }else{
                        reject(res.errMessage)
                    }
                })
            })
        },
        getData(){
            let _this = this;
            const params = {
                'brandId': _this.brandId,
                'storehouseId': _this.storehouseId,
                'areaId': _this.areaId,
                'goodsId': _this.goodsId,
                'cateId': _this.cateId,
                'grade': _this.grade,
                'colorId': _this.colorId,
                'specId': _this.specId,
                'startTime': _this.startTime,
                'endTime': _this.endTime,
                'statisticalDate': _this.statisticalDate,
                'type': '0',
                'stauts': _this.status,
                'page': _this.page - 1,
                'size': _this.size,
            }
            _this.isload = true;
            queryGoodsPurchaseForm(params)
            .then(res => {
                _this.isload = false;
                if(res.success){
                    _this.dataList = res.data.content;
                    _this.total = res.data.totalElements;
                    _this.totalAmount = res.data.totalAmount;
                }else{
                    _this.$notification['error']({
                        message: '提示',
                        description: res.errMessage,
                        duration: 8,
                    })
                }
            })
        },
        // 获取商品说明和备注
        getDescription(type){
            let _this = this;
            return new Promise((resolve,reject) => {
                const params = {
                    'brandId':_this.brandId,
                    'type': type,
                    'page': 0,
                    'size': 99,
                };
                queryGoodsCommonConfig(params)
                .then(res=>{
                    if(res.success){
                        if(type == '2'){
                            _this.colorsList = res.data.content;
                        }else if(type == '3'){
                            _this.gradeList = res.data.content;
                        }else if(type == '4'){
                            _this.specList = res.data.content;
                        }else if(type == '5'){
                            _this.descriptionList = res.data.content;
                        }else{
                            _this.remarkList = res.data.content;
                        }
                        resolve();
                    }else{
                        reject(res.errMessage)
                    }
                })
            })
        },
        // 分页
        handleTableChange(pagination, filters, sorter) {
            console.log(pagination);
            this.page = pagination.current;
            this.size = pagination.pageSize;
            this.getData()
        },
        onChange(date, dateString) {
            console.log(date, dateString);
            if(date.length != 0){
                this.startTime = dateString[0];
                this.endTime = dateString[1];
            }else{
                this.startTime = '';
                this.endTime = '';
            }
            this.getData()
        },
        // 新增下单
        add(){
            this.item.goodsId = undefined;
            this.item.purchaseQuantity = '';
            this.visible = true;
        },
        handleOk(){
            let _this = this;
            if(_this.item.goodsId === undefined){
                _this.$message.warning('请选择商品');
                return
            }
            if(_this.item.purchaseQuantity === ''){
                _this.$message.warning('请输入下单数量');
                return
            }
            _this.confirmLoading = true
            const params = {
                'brandId': _this.brandId,
                'storehouseId': _this.storehouseId,
                'areaId': _this.areaId,
                'goodsId': _this.item.goodsId.split(',')[0],
                'goodsDetailsId': _this.item.goodsId.split(',')[1],
                'purchaseQuantity': _this.item.purchaseQuantity,
            }
            createGoodsPurchaseForm(params)
            .then(res => {
                _this.confirmLoading = false
                if(res.success){
                    _this.$notification['success']({
                        message: '提示',
                        description: '提交成功',
                        duration: 8,
                    })
                    _this.visible = false;
                    _this.getData();
                }else{
                    _this.$notification['error']({
                        message: '提示',
                        description: res.errMessage,
                        duration: 8,
                    })
                }
            })
        },
        // 收货人员操作下单数据
        update(item,type){
            this.receiverStatus = type;
            this.receiverItem = JSON.parse(JSON.stringify(item));
            this.receiveQuantity = '';
            this.latestReservePrice = '';
            this.remarks = '';
            this.receiverVisible = true;
        },
        receiverHandleOk(){
            let _this = this;
            _this.receiverConfirmLoading = true;
            const params = {
                'receiveQuantity': _this.receiveQuantity,
                'remarks': _this.remarks,
                'latestReservePrice': _this.latestReservePrice,
                'status': _this.receiverStatus,
                'id': _this.receiverItem.id,
            }
            updateGoodsPurchaseFormByReceiver(params)
            .then(res => {
                _this.receiverConfirmLoading = false;
                if(res.success){
                    _this.$notification['success']({
                        message: '提示',
                        description: '操作成功',
                        duration: 8,
                    })
                    _this.receiverVisible = false;
                    _this.getData();
                }else{
                    _this.$notification['error']({
                        message: '提示',
                        description: res.errMessage,
                        duration: 8,
                    })
                }
            })
        },
        // 客服确认上单
        serviceUpdate(item){
            this.serviceItem = JSON.parse(JSON.stringify(item));
            // this.addStockQuantity = item.purchaseQuantity;
            this.serviceVisible = true;
        },
        serviceHandleOk(){
            let _this = this;
            const params = {
                'id': _this.serviceItem.id,
                'purchaseQuantity': _this.serviceItem.purchaseQuantity,
                // 'addStockQuantity': _this.addStockQuantity,
                'confirmAddStock': '1',
            }
            _this.serviceConfirmLoading = true;
            updateGoodsPurchaseFormByCustomer(params)
            .then(res => {
                _this.serviceConfirmLoading = false;
                if(res.success){
                    _this.$notification['success']({
                        message: '提示',
                        description: '操作成功',
                        duration: 8,
                    })
                    _this.serviceVisible = false;
                    _this.getData();
                }else{
                    _this.$notification['error']({
                        message: '提示',
                        description: res.errMessage,
                        duration: 8,
                    })
                }
            })
        },
        del(item){
            let _this = this;
            const params = {
                'id': item.id,
                'purchaseQuantity': item.purchaseQuantity,
                'isDelete': '1',
            }
            updateGoodsPurchaseFormByCustomer(params)
            .then(res => {
                _this.serviceConfirmLoading = false;
                if(res.success){
                    _this.$notification['success']({
                        message: '提示',
                        description: '删除成功',
                        duration: 8,
                    })
                    _this.getData();
                }else{
                    _this.$notification['error']({
                        message: '提示',
                        description: res.errMessage,
                        duration: 8,
                    })
                }
            })
        }
    }
}

</script>
<style scoped>
.purchase /deep/ .ant-table-footer{
    background: #F5F5F5;
}
</style>